package lib

import (
	"github.com/kevin186/casbin/models"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

var DB *gorm.DB

func initDB() {
	//dsn := "root:admin@tcp(101.43.132.73:30306)/mycasbin?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := "root:nancal.123@tcp(192.168.31.156:3306)/testcasbintest?charset=utf8mb4&parseTime=True&loc=Local"
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      true,
		},
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		log.Fatal("Failed to connect to the database:", err)
	}
	DB = db
}

func Migrate() {
	err := DB.AutoMigrate(&models.User{}, &models.Role{}, &models.Router{})
	if err != nil {
		panic(err)
	}
}
